package com.xyy.saas.payment.adpater.xydLoan.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.adpater.xydLoan.core.constants.XydApiAddress;
import com.xyy.saas.payment.adpater.xydLoan.core.dto.XydAuthCreditDto;
import com.xyy.saas.payment.adpater.xydLoan.core.dto.XydCreditResultDto;
import com.xyy.saas.payment.cores.vo.XydAccountBalanceDto;
import com.xyy.saas.payment.cores.vo.XydGetFileDto;
import com.xyy.saas.payment.adpater.xydLoan.core.dto.XydLoanResultDto;
import com.xyy.saas.payment.adpater.xydLoan.core.req.*;
import com.xyy.saas.payment.adpater.xydLoan.core.resp.XydAuthCreditResp;
import com.xyy.saas.payment.adpater.xydLoan.core.resp.XydSearchCreditResultResp;
import com.xyy.saas.payment.adpater.xydLoan.core.resp.XydSearchLoanResultResp;
import com.xyy.saas.payment.adpater.xydLoan.support.XydLoanClient;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PayBizException;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.util.AmountCastUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @author wangzeqi
 */
@Slf4j
@Component
public class XydLoanService {

    @Value("${xydLoad.productNo:yaobangmang}")
    private String xydLoadPlatformCode;
    @Value("${xydLoad.platformCode:GYL-YCD-CGD}")
    private String xydLoadProductNo;

    //private static final String xydLoadPlatformCode = ApolloUtil.getProperty("xydLoad.productNo", "yaobangmang");
    //private static final String xydLoadProductNo = ApolloUtil.getProperty("xydLoad.platformCode", "GYL-YCD-CGD");

    private final XydLoanClient xydLoanClient;

    public XydLoanService(XydLoanClient xydLoanClient) {
        this.xydLoanClient = xydLoanClient;
    }

    /**
     * 获取授信h5地址
     */
    @SneakyThrows
    public XydAuthCreditResp authCredit(XydAuthCreditReq xydAuthCreditReq) {
        String logScene = "获取授信h5地址";
        XydAuthCreditResp xydAuthCreditResp =new XydAuthCreditResp();
        String jsonParam = "";
        try {
        checkAuthCreditParam(xydAuthCreditReq);
        fillXydBaseRequestParam(xydAuthCreditReq);
        jsonParam = JSON.toJSONString(xydAuthCreditReq);
        xydAuthCreditResp = xydLoanClient.execute(logScene, XydApiAddress.authCredit, jsonParam, XydAuthCreditResp.class);
        }catch (PaymentException e){
            log.error("##authCredit--error, param:{}", JSON.toJSONString(xydAuthCreditReq), e);
            xydAuthCreditResp.setCode(e.getErrCode());
            xydAuthCreditResp.setMsg(e.getErrMsg());
            return xydAuthCreditResp;
        }catch (Exception e){
            log.error("##authCredit--error, param:{}", JSON.toJSONString(xydAuthCreditReq), e);
            throw new PaymentException(ResultCodeEnum.XYDLOAN_RESPONSE_ERROR,e.getMessage());
        }
        if (xydAuthCreditResp == null ||StringUtils.isEmpty(xydAuthCreditResp.getH5Url())) {
            log.error("{} response is null, param:{}", logScene, jsonParam);
            throw new PaymentException(ResultCodeEnum.XYDLOAN_RESPONSE_ERROR);
        }
        return xydAuthCreditResp;
    }

    @SneakyThrows
    private void checkAuthCreditParam(XydAuthCreditReq xydAuthCreditReq) {
        XydAuthCreditDto authDto = xydAuthCreditReq.getAuth();
        if (authDto == null) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR);
        }

        if (StringUtils.isBlank(authDto.getDeviceNo()) ||
                StringUtils.isBlank(authDto.getThirdUserNo()) ||
                StringUtils.isBlank(authDto.getBusinessLicense())) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR);
        }

    }

    private void fillXydBaseRequestParam(XydLoanBaseRequest xydLoanBaseRequest) {
        xydLoanBaseRequest.setProductNo(xydLoadProductNo);
        xydLoanBaseRequest.setPlatformCode(xydLoadPlatformCode);
    }

    /**
     * 提款时获取H5授权地址
     */
    public XydAuthCreditResp authLoan(XydPayAuthLoanReq xydPayAuthLoanReq) throws PaymentException {
        String logScene = "提款时获取H5授权地址";
        checkXydPayAuthLoanReq(xydPayAuthLoanReq);
        fillXydBaseRequestParam(xydPayAuthLoanReq);
        String jsonParam = JSON.toJSONString(xydPayAuthLoanReq);
        XydAuthCreditResp xydAuthCreditResp = xydLoanClient.execute(logScene, XydApiAddress.authLoan, jsonParam, XydAuthCreditResp.class);

        if (xydAuthCreditResp == null) {
            log.error("{} response is null, param:{}", logScene, jsonParam);
            throw new PaymentException(ResultCodeEnum.XYDLOAN_RESPONSE_ERROR);
        }
        return xydAuthCreditResp;
    }

    private void checkXydPayAuthLoanReq(XydPayAuthLoanReq xydPayAuthLoanReq) {

    }

    /**
     * 查询放款结果
     */
    public XydLoanResultDto searchLoanResult(XydSearchLoanResultReq xydSearchLoanResultReq) throws PaymentException {
        String logScene = "查询放款结果";
        checkSearchLoanResultParam(xydSearchLoanResultReq);
        fillXydBaseRequestParam(xydSearchLoanResultReq);
        String jsonParam = JSON.toJSONString(xydSearchLoanResultReq);
        XydSearchLoanResultResp xydSearchLoanResultResp = xydLoanClient.execute(logScene, XydApiAddress.searchLoanResult, jsonParam, XydSearchLoanResultResp.class);
        return xydSearchLoanResultResp.getLoanResult();
    }

    public XydLoanResultDto searchLoanResult(String thirdOrderNo, String thirdUserNo) throws PaymentException {
        XydSearchLoanResultReq xydSearchLoanResultReq = new XydSearchLoanResultReq()
                .setThirdOrderNo(thirdOrderNo)
                .setThirdUserNo(thirdUserNo);
        return searchLoanResult(xydSearchLoanResultReq);
    }

    /**
     * 查询用户授信结果
     */
    public XydCreditResultDto searchCreditResult(String thirdUserNo, String businessLicense) throws PaymentException {
        if (StringUtils.isBlank(thirdUserNo) || StringUtils.isBlank(businessLicense)) {
            throw new PayBizException(ResultCodeEnum.PARAM_ERROR);
        }
        XydSearchCreditResultReq req = new XydSearchCreditResultReq();
        req.setThirdUserNo(thirdUserNo);
        req.setBusinessLicense(businessLicense);
        fillXydBaseRequestParam(req);
        String jsonStr = JSON.toJSONString(req);
        XydSearchCreditResultResp resp = xydLoanClient.execute(Constants.XYD_CREDIT_RESULT, XydApiAddress.searchCreditResult, jsonStr, XydSearchCreditResultResp.class);
        if (resp != null && resp.getCreditResult() != null) {
            XydCreditResultDto creditResult = resp.getCreditResult();
            creditResult.setCreditAmount(AmountCastUtil.formatBigDecimal2PercentInt(creditResult.getCreditAmount()));
            creditResult.setAvailableCreditAmount(AmountCastUtil.formatBigDecimal2PercentInt(creditResult.getAvailableCreditAmount()));
            return resp.getCreditResult();
        }
        return null;
    }

    /**
     * 取消放款
     */
    public void loanCancel(XydLoanCancelReq xydLoanCancelReq) throws PaymentException {
        String logScene = "取消放款";
        checkLoanCancelParam(xydLoanCancelReq);
        fillXydBaseRequestParam(xydLoanCancelReq);
        String jsonParam = JSON.toJSONString(xydLoanCancelReq);
        xydLoanClient.execute(logScene, XydApiAddress.loanCancel, jsonParam, null);
    }


    private void checkLoanCancelParam(XydLoanCancelReq xydLoanCancelReq) {

    }

    private void checkSearchLoanResultParam(XydSearchLoanResultReq xydSearchLoanResultReq) {

    }

    /**
     * 贷中数据同步
     *
     * @param xydLoanDataSyncReq
     * @return
     */
    public boolean loanDataSync(XydLoanDataSyncReq xydLoanDataSyncReq) {

        String logScene = "贷中数据同步";

        fillXydBaseRequestParam(xydLoanDataSyncReq);
        String jsonParam = JSON.toJSONString(xydLoanDataSyncReq);
        try {
            xydLoanClient.execute(logScene, XydApiAddress.loanDataSync, jsonParam, null);
        } catch (PaymentException e) {
            return false;
        }
        return true;
    }


    /**
     * 退货
     * @param xydLoanSalesReturnReq
     * @return
     */
    public void loanSalesReturn(XydLoanSalesReturnReq xydLoanSalesReturnReq) throws PaymentException {
        String logScene = "退货";
        fillXydBaseRequestParam(xydLoanSalesReturnReq);
        String jsonParam = JSON.toJSONString(xydLoanSalesReturnReq);
        xydLoanClient.execute(logScene, XydApiAddress.loanSalesReturn, jsonParam, null);
    }

    /**
     * 获取对账文件
     */
    public List<XydGetFileDto> getFile(XydGetFileReq fileReq) throws PaymentException {
        String jsonStr = JSON.toJSONString(fileReq);
        String dtoStr = xydLoanClient.execute(Constants.XYD_GET_FILE, XydApiAddress.GET_FILE, jsonStr, String.class);
        if (StringUtils.isNotEmpty(dtoStr)) {
            return JSON.parseArray(dtoStr, XydGetFileDto.class);
        }
        return Collections.emptyList();
    }

    /**
     * 查询账户余额
     */
    public XydAccountBalanceDto queryAccountBalance(XydAccountBalanceReq accountBalanceReq) throws PaymentException {
        String jsonStr = JSON.toJSONString(accountBalanceReq);
        String resultStr = xydLoanClient.execute(Constants.XYD_QUERY_ACCOUNT_BALANCE, XydApiAddress.QUERY_ACCOUNT_BALANCE, jsonStr, String.class);

        if (StringUtils.isNotEmpty(resultStr)) {
            List<XydAccountBalanceDto> dtoList = JSON.parseArray(resultStr, XydAccountBalanceDto.class);
            if (CollUtil.isNotEmpty(dtoList)) {
                return dtoList.get(0);
            }
        }
        return null;
    }
}
